

from django.shortcuts import render
from django.http import HttpResponse
from .signals import user_visited, user_activity
from django.contrib.auth.models import AnonymousUser
from .models import CustomUser
import time

def home(request):
    # 获取用户（真实或匿名）
    user = request.user if request.user.is_authenticated else AnonymousUser()

    print("user-------------->", user, " ----------------- ", request)
    
    # 发送用户访问信号
    meta = {
        'ip': request.META.get('REMOTE_ADDR'),
        'path': request.path,
        'method': request.method,
        'user_agent': request.META.get('HTTP_USER_AGENT', '')
    }
    user_visited.send(sender=home, user=user, request_meta=meta)
    
    # 模拟用户活动
    if isinstance(user, CustomUser):
        # 发送用户活动信号
        user_visited.send(
            sender=home,
            user=user,
            request_meta={
                'ip': request.META.get('REMOTE_ADDR'),
                'path': request.path,
                'method': request.method,
                'user_agent': request.META.get('HTTP_USER_AGENT', '')
            }
        )
            
    return HttpResponse("欢迎来到 Django 首页！")

def about(request):
    user = request.user if request.user.is_authenticated else AnonymousUser()
    
    # 发送用户访问信号
    meta = {
        'ip': request.META.get('REMOTE_ADDR'),
        'path': request.path,
        'method': request.method
    }
    user_visited.send(sender=about, user=user, request_meta=meta)
    
    # 模拟用户活动
    if isinstance(user, CustomUser):
        # 发送用户活动信号
        user_activity.send(
            sender=about,
            user=user,
            activity_type='page_view',
            details={'page': 'about'}
        )
    
    return render(request, 'about.html', {'name': '小明'})